﻿using System.Collections.Generic;
using System.Linq;
using Microsoft.Practices.Prism.Commands;
using Microsoft.Practices.Prism.Interactivity.InteractionRequest;
using Okazuki.MVVM.PrismSupport.Utils;
using Okazuki.MVVM.PrismSupport.ViewModels;

namespace InvokeCommandActionWithEventArgs
{
    public class MainWindowViewModel : ViewModelBase
    {
        /// <summary>
        /// 現在選択中のアイテムのリスト
        /// </summary>
        private List<Person> selectedItems = new List<Person>();

        /// <summary>
        /// ListBoxのItemsSourceにバインドされます
        /// </summary>
        [AutoInit]
        public List<Person> People { get; set; }

        /// <summary>
        /// 選択中人物の平均年齢を取得します
        /// </summary>
        public double Average
        {
            get
            {
                return selectedItems.Count > 0 ? 
                    selectedItems.Average(p => p.Age) : 0;
            }
        }

        /// <summary>
        /// メッセージボックス表示用
        /// </summary>
        [AutoInit]
        public InteractionRequest<Notification> AlertRequest { get; private set; }

        /// <summary>
        /// 平均年齢を計算するコマンド
        /// </summary>
        [AutoInitCommand]
        public DelegateCommand<SelectionChangedCommandParameter<Person>> CalcAverageCommand { get; private set; }

        /// <summary>
        /// CalcAverageCommandの実装メソッド
        /// </summary>
        [CommandMethod]
        private void CalcAverageExecute(SelectionChangedCommandParameter<Person> parameter)
        {
            parameter.RemovedItems.ForEach(p => selectedItems.Remove(p));
            selectedItems.AddRange(parameter.AddedItems);

            base.RaisePropertyChanged(() => Average);
        }

        /// <summary>
        /// 選択数を表示させるコマンド
        /// </summary>
        [AutoInitCommand]
        public DelegateCommand<string> ShowCountCommand { get; private set; }

        /// <summary>
        /// ShowCountCommandの実装メソッド
        /// </summary>
        [CommandMethod]
        private void ShowCountExecute(string parameter)
        {
            this.AlertRequest.Raise(
                new Notification { Content = parameter });
        }

        /// <summary>
        /// ShowCountCommandの実行可否を取得します
        /// </summary>
        [CommandMethod]
        private bool CanShowCountExecute(string parameter)
        {
            return !string.IsNullOrEmpty(parameter);
        }
    }

    public class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }
}
